using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UILevelBuff : UIEntityWindow
    {
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UILevelBuff),
            layer = EUILayer.Normal,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #region Template Generate,don't modify

        protected class UIB_UIBuffTips
        {
            #region ObjectBinding Generate

            public ExButton btnClose { protected set; get; }
            public ExText buffName { protected set; get; }
            public ExText buffTime { protected set; get; }
            public ExText buffCountDown { protected set; get; }
            public ExText buffDes { protected set; get; }
            public GameObject buffItem { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<ExButton>("btnClose", out var __tbv0);
                btnClose = __tbv0;
                __binding.TryGetVariableValue<ExText>("buffName", out var __tbv1);
                buffName = __tbv1;
                __binding.TryGetVariableValue<ExText>("buffTime", out var __tbv2);
                buffTime = __tbv2;
                __binding.TryGetVariableValue<ExText>("buffCountDown", out var __tbv3);
                buffCountDown = __tbv3;
                __binding.TryGetVariableValue<ExText>("buffDes", out var __tbv4);
                buffDes = __tbv4;
                __binding.TryGetVariableValue<GameObject>("buffItem", out var __tbv5);
                buffItem = __tbv5;
            }




            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify

        protected UIB_UIBuffTips ui { get; set; }
        private UIMsgDispatcher currMsgDispatcher => _msgDispatcher as UIMsgDispatcher;

        #region Field

        private List<LevelBuffData> _levelBuff;
        private LevelBuffData _curBuffData;
        private long _endTime;

        private ListScrollAdapter<UIN_LevelBuffToggle> _buffItems;
        private ExText _buffName;
        private ExText _timeDescription;
        private ExText _leftTime;
        private ExText _buffDescription;

        #endregion

        #region Override

        protected override void BeforeInit()
        {
            ui = new UIB_UIBuffTips();
            ui.InitBinding(csObjBind);
        }

        protected override void OnInit()
        {
            _levelBuff = new List<LevelBuffData>();
            UpdateBuffData();

            ui.btnClose.onClick.AddListener(Close);
            _buffName = ui.buffName;
            _timeDescription = ui.buffTime;
            _leftTime = ui.buffCountDown;
            _buffDescription = ui.buffDes;
            _buffItems = InitListScroll<UIN_LevelBuffToggle>(ui.buffItem, RefreshBuffItem);
            _buffItems.InitUnitSelected(UnitSelectType.ByExToggle, OnBuffItemClicked);
            isUpdate = true;
        }

        private void OnBuffItemClicked(int index, UIN_LevelBuffToggle item)
        {
            RefreshBuffDetail(_levelBuff[index]);
        }

        protected override void OnShow(UIBaseData data)
        {
            _buffItems.RefillCells(_levelBuff.Count, 0);
        }

        protected override void OnHide()
        {

        }

        protected override void AddMsgListeners()
        {
            //buff添加，参数：buffData，isNew
            currMsgDispatcher.AddListener<LevelBuffData, bool, LevelBuffHostType, long>(MsgEventType.Level_UpdateBuff,
                OnLevelBuffUpdate);
            //buff移除，参数：buffData
            currMsgDispatcher.AddListener<LevelBuffData, LevelBuffHostType, long>(MsgEventType.Level_RemoveBuff,
                OnLevelBuffRemove);
        }

        protected override void OnUpdate(float dt, float unscaledDt)
        {
            if (_curBuffData.endTime < GameServerModule.Instance.ServerTimestamp)
            {
                return;
            }

            _leftTime.text = APIUIConst.SecondsToHMS(_endTime - GameServerModule.Instance.ServerTimestamp);
        }

        protected override void OnDispose()
        {
            RenderBlurUtil.ReleaseBlurRT(nameof(UILevelBuff));
        }

        #endregion

        #region Method

        private void RefreshBuffItem(UIN_LevelBuffToggle item, int index)
        {
            item.ShowByData(_levelBuff[index]);
        }


        private void RefreshBuffDetail(LevelBuffData buffData)
        {
            _curBuffData = buffData;
            _endTime = buffData.endTime;
            _buffName.text = buffData.cfgBuff.Name;
            _timeDescription.text = APIUIConst.GetBuffTimeDescription();
            _leftTime.text = APIUIConst.SecondsToHMS(_endTime - GameServerModule.Instance.ServerTimestamp);
            _buffDescription.text = $"{buffData.cfgBuff.Describe}\n{buffData.cfgBuff.InterestDescribe}";
        }

        private void UpdateBuffData()
        {
            _levelBuff.Clear();
            var buffDataCollection = LevelPlayUtil.GetDynLevelPlayer().buffs;
            foreach (var buffData in buffDataCollection)
            {
                _levelBuff.Add(buffData);
            }
        }

        private void OnLevelBuffRemove(LevelBuffData buffData, LevelBuffHostType hostType, long hostId)
        {
            var selectIndex = _buffItems.selectedIndex;
            var removeIndex = _levelBuff.IndexOf(buffData);
            UpdateBuffData();
            //没有buff了，关闭界面
            if (_levelBuff.Count == 0)
            {
                Close();
                return;
            }

            //移除的buff index在选中index之后 直接刷新
            if (selectIndex < removeIndex)
            {
                _buffItems.RefillCells(_levelBuff.Count, selectIndex);
            }
            //移除的buff index在选中index之前 或者正好移除选中buff 选中index - 1,最小为0
            else
            {
                var newSelectIndex = selectIndex - 1 > 0 ? selectIndex - 1 : 0;
                _buffItems.RefillCells(_levelBuff.Count, newSelectIndex);
            }
        }

        private void OnLevelBuffUpdate(LevelBuffData buffData, bool isNew, LevelBuffHostType hostType, long hostId)
        {
            UpdateBuffData();
            _buffItems.RefillCells(_levelBuff.Count);
        }

        #endregion
    }
}